package com.mathdroid.core;

import java.awt.Component;
import java.awt.FontMetrics;

import javax.swing.SwingUtilities;

/**
 * This contains custom utility methods for strings.
 */
public final class DroidStringWorker {
	
	/**
	 * The maximum line length in a tooltip.
	 */
	private static final int MAX_LINE_LENGTH = 60;

	/**
	 * Inserts HTML breaks every "MAX_LINE_LENGTH" characters. The break is 
	 * inserted in the first possible whitespace before the length. So words
	 * are not cut in a half.
	 * @param s The string to format.
	 * @return Formated string.
	 */
	public String insertBreaks(final String s) {
		String newString = "";
		
		if (s.length() > MAX_LINE_LENGTH) {
			for (int j = MAX_LINE_LENGTH; j > 0; j--) {
				if (s.charAt(j) == ' ') {
					String part0 = s.substring(0, j);
					String part1 = s.substring(j + 1, s.length());
					newString = part0 + "<br>" + this.insertBreaks(part1);
					j = 0;
				}
			}
		}
		
		if (newString.equals("")) {
			newString = s;
		}
		
		return newString;
	}
	
	/**
	 * Get the text width in pixels of a text with a given font.
	 * @param c The swing component.
	 * @param s The text.
	 * @return Text width in pixels.
	 */
	public int textWidth(final Component c, final String s) {
		FontMetrics fm = c.getFontMetrics(c.getFont());
		final int width = SwingUtilities.computeStringWidth(
				fm, s);
		return width;
	}
}
